/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.celularessuc.gco.ui;

import com.jjsoft.celularessuc.gco.mdl.Articulo;
import com.jjsoft.celularessuc.gco.mdl.Cliente;
import com.jjsoft.celularessuc.gco.mdl.Detalleproforma;
import com.jjsoft.celularessuc.gco.mdl.Proforma;
import com.jjsoft.celularessuc.gco.mdl.Serie;
import com.jjsoft.celularessuc.gco.neg.ArticuloManager;
import com.jjsoft.celularessuc.gco.neg.CImprimir;
import com.jjsoft.celularessuc.gco.neg.ProformaManager;
import com.jjsoft.celularessuc.gco.neg.SecuenciaManager;
import com.jjsoft.celularessuc.gco.neg.SerieManager;
import com.jjsoft.celularessuc.gco.util.CNumeros;
import com.jjsoft.celularessuc.gco.util.CSelecciones;
import com.jjsoft.celularessuc.gco.util.MiModelo;
import com.jjsoft.celularessuc.gco.util.Validacion;
import com.jjsoft.celularessuc.gco.util.configuraciones;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;

/**
 *
 * @author johnny
 */
public class VProforma extends javax.swing.JFrame {

    /**
     * Creates new form VProforma
     */
    Articulo objArt;
    MiModelo modelo = new MiModelo();
    Cliente cli;
    JTextField texto;
    Date d = new Date();
    Proforma proforma;
    ArticuloManager am = new ArticuloManager();
    SerieManager sm = new SerieManager();
    SecuenciaManager sqm = new SecuenciaManager();
    public VProforma(Cliente cli) {
        setIconImage(new ImageIcon(getClass().getResource("/img/1362798841_CellPhone.png")).getImage());
        initComponents();
        txtNumero.setText(String.valueOf(sqm.obtenerSecuencia(configuraciones.getInstance().getSucursal())));
        cmdAgregar.setMnemonic(KeyEvent.VK_A);
        cmdGuardar.setMnemonic(KeyEvent.VK_G);
        cmdQuitar.setMnemonic(KeyEvent.VK_Q);
        this.cli = cli;
        this.txtCedula.setText(cli.getCedula());
        this.txtCliente.setText(cli.getNombres() + " " + cli.getApellidos());
        this.txtTelefono.setText(cli.getTelefono());
        this.txtDireccion.setText(cli.getDireccion());
        this.txtFecha.setText(this.d.getDate() + "-" + (this.d.getMonth() + 1) + "-" + (this.d.getYear() + 1900));
        String[] identificadores = {"CANT", "DESCRIPCION", "P. UNIT", "V. VENTA"};
        this.modelo.setColumnIdentifiers(identificadores);
        this.dtgProforma.setModel(this.modelo);
        this.dtgProforma.getColumn("CANT").setPreferredWidth(30);
        this.dtgProforma.getColumn("DESCRIPCION").setPreferredWidth(330);
        this.dtgProforma.getColumn("P. UNIT").setPreferredWidth(50);
        this.dtgProforma.getColumn("V. VENTA").setPreferredWidth(50);
        proforma = new Proforma();
        proforma.setCedulaCliente(cli);
        proforma.setDetalleproformaList(new ArrayList<Detalleproforma>());

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mnuAcciones = new javax.swing.JPopupMenu();
        mnuQuitar = new javax.swing.JMenuItem();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtCliente = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtTelefono = new javax.swing.JTextField();
        txtCedula = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtFecha = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtNumero = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtDireccion = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgProforma = new javax.swing.JTable();
        txtCodigo = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        txtPrecio = new javax.swing.JTextField();
        cmdAgregar = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        txtSubtotal = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        txtSubtotalD = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        txtIVA = new javax.swing.JTextField();
        cmdQuitar = new javax.swing.JButton();
        cmdGuardar = new javax.swing.JButton();
        txtDescuento = new javax.swing.JSpinner();
        jLabel16 = new javax.swing.JLabel();
        txtTotal = new javax.swing.JTextField();
        txtCantidad = new javax.swing.JSpinner();
        jLabel17 = new javax.swing.JLabel();

        mnuQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.png"))); // NOI18N
        mnuQuitar.setText("Quitar");
        mnuQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuQuitarActionPerformed(evt);
            }
        });
        mnuAcciones.add(mnuQuitar);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Egreso de Mercadería");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(51, 51, 51));
        jLabel3.setText("Cliente:");

        txtCliente.setEditable(false);
        txtCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtClienteActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(51, 51, 51));
        jLabel4.setText("RUC / C.I:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(51, 51, 51));
        jLabel5.setText("Telf:");

        txtTelefono.setEditable(false);

        txtCedula.setEditable(false);
        txtCedula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCedulaActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setForeground(new java.awt.Color(51, 51, 51));
        jLabel6.setText("Fecha de Emision:");

        txtFecha.setEditable(false);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setForeground(new java.awt.Color(51, 51, 51));
        jLabel7.setText("Numero:");

        txtNumero.setEditable(false);
        txtNumero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNumeroActionPerformed(evt);
            }
        });
        txtNumero.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtNumeroKeyReleased(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(51, 51, 51));
        jLabel2.setText("Direccion:");

        txtDireccion.setEditable(false);

        dtgProforma.setComponentPopupMenu(mnuAcciones);
        dtgProforma.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setViewportView(dtgProforma);

        txtCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodigoActionPerformed(evt);
            }
        });
        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCodigoKeyReleased(evt);
            }
        });

        jLabel9.setText("Codigo:");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/search-database.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel10.setText("Cantidad:");

        jLabel11.setText("P. Unit");

        txtPrecio.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPrecioKeyReleased(evt);
            }
        });

        cmdAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/add.png"))); // NOI18N
        cmdAgregar.setText("Agregar");
        cmdAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAgregarActionPerformed(evt);
            }
        });

        jLabel12.setText("Subtotal_0:");

        txtSubtotal.setEnabled(false);

        jLabel13.setText("Descuento:");

        jLabel14.setText("Subtotal_D:");

        txtSubtotalD.setEnabled(false);

        jLabel15.setText("IVA:");

        txtIVA.setEnabled(false);

        cmdQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.png"))); // NOI18N
        cmdQuitar.setText("    Quitar");
        cmdQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdQuitarActionPerformed(evt);
            }
        });

        cmdGuardar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cmdGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save.png"))); // NOI18N
        cmdGuardar.setText("     GUARDAR");
        cmdGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdGuardarActionPerformed(evt);
            }
        });

        txtDescuento.setModel(new javax.swing.SpinnerNumberModel(0, 0, 100, 1));
        txtDescuento.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                txtDescuentoStateChanged(evt);
            }
        });

        jLabel16.setText("Total:");

        txtTotal.setEditable(false);
        txtTotal.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        txtTotal.setForeground(new java.awt.Color(255, 0, 0));

        txtCantidad.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));

        jLabel17.setText("%");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 572, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(390, 390, 390))))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(205, 205, 205)
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel11)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cmdAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(cmdQuitar)
                                    .addComponent(cmdGuardar))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel13, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel12, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel16, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel14, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel15, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(txtDescuento, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
                                        .addComponent(txtSubtotal)
                                        .addComponent(txtSubtotalD, javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(txtIVA, javax.swing.GroupLayout.Alignment.TRAILING))
                                    .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel7)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                            .addComponent(txtDireccion, javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(txtCedula, javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel6)
                                            .addComponent(jLabel5))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(txtFecha, javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(txtTelefono, javax.swing.GroupLayout.Alignment.LEADING)))
                                    .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(jSeparator1))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel17)
                .addGap(29, 29, 29))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel9)
                        .addComponent(jLabel10)
                        .addComponent(jLabel11)
                        .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(cmdAgregar)
                        .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(txtSubtotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdQuitar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(txtDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel17))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtSubtotalD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel14))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel15)
                            .addComponent(txtIVA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel16)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(cmdGuardar)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(668, 671));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txtCedulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCedulaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCedulaActionPerformed

    private void txtClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtClienteActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtClienteActionPerformed

    private void txtCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == 10) {

            CSelecciones.articulo = am.buscarPorCodigo(txtCodigo.getText(), configuraciones.getInstance().getSucursal());

            if (CSelecciones.articulo == null) {
                JOptionPane.showMessageDialog(rootPane, "No se encontro el artículo", "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                txtPrecio.setText(CSelecciones.articulo.getPventa().toString());
            }
        }
    }//GEN-LAST:event_txtCodigoKeyPressed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        CSelecciones.texto1 = txtCodigo;
        CSelecciones.texto2 = txtPrecio;
        CSelecciones.texto3=new JTextField();
        new VSeleccionArticulo(true).setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cmdAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAgregarActionPerformed
        // TODO add your handling code here:
        if (CSelecciones.articulo != null) {
            double precio = 0;
            try {
                precio = Double.parseDouble(txtPrecio.getText()) / (1 + configuraciones.getInstance().getConfiguracion().getIva() / 100d);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(rootPane, "Campo precio incorrecto", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if(CSelecciones.articulo.getStock()<Integer.parseInt(String.valueOf(txtCantidad.getValue())))
            {
                JOptionPane.showMessageDialog(rootPane, "No existen sufucientes artículos en stock");
                return;
            }
            String serie = buscarSerie();
            if (serie == null) {
                limpiaTodo();
                return;
            }
            if (serie.equals("")) {
                agregarArticulo(precio, serie, Integer.parseInt(String.valueOf(txtCantidad.getValue())));
            } else {
                int cantidadAgregar = Integer.parseInt(String.valueOf(txtCantidad.getValue()));
                txtCantidad.setValue(1);
                for (int i = 0; i < cantidadAgregar - 1; i++) {
                    if (serie != null) {
                        agregarArticulo(precio, serie, 1);
                    }

                    serie = buscarSerie();
                }
                if (serie != null) {
                    agregarArticulo(precio, serie, 1);
                }
            }
            limpiaTodo();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Primero Seleccione un artículo", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
    }//GEN-LAST:event_cmdAgregarActionPerformed

    private void txtDescuentoStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_txtDescuentoStateChanged
        // TODO add your handling code here:
        Calcular();
    }//GEN-LAST:event_txtDescuentoStateChanged

    private void cmdQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdQuitarActionPerformed
        // TODO add your handling code here:

        if (dtgProforma.getSelectedRow() != -1) {
            if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro", "Quitar Articulo", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                int i = dtgProforma.getSelectedRow();
                modelo.removeRow(i);
                proforma.getDetalleproformaList().remove(i);
                Calcular();
            }

        } else {
            JOptionPane.showMessageDialog(rootPane, "Primero Seleccione un articulo", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_cmdQuitarActionPerformed

    private void cmdGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdGuardarActionPerformed
        // TODO add your handling code here:
        if (proforma.getDetalleproformaList().size() > 0) {

            if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro de guardar la proforma?", "Guardar Proforma", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                proforma.setFechaEmision(d);
                proforma.setEstado(0);
                proforma.setIdSucursal(configuraciones.getInstance().getSucursal());
                proforma.setNumero(Integer.parseInt(txtNumero.getText()));
                ProformaManager fm = new ProformaManager();
                fm.guardarProforma(proforma);
                sqm.aumentarSecuencia(configuraciones.getInstance().getSucursal());
                VPrincipal.getInstance().cambiaCaja(configuraciones.getInstance().getDiario().getValor());
                VMantenimientoArticulos.getInstance().actualizaStocks();
                if (JOptionPane.showConfirmDialog(rootPane, "Proforma guardada correctamente\nDesea imprimirla?", "Imprimir Proforma", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                      new CImprimir().imprimirProforma(proforma);
                }
                this.dispose();
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "No ha registrado artículos a vener", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_cmdGuardarActionPerformed

    private void txtNumeroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumeroKeyReleased
        // TODO add your handling code here:
        Validacion validar = new Validacion();
        validar.numeros(evt, txtNumero);
    }//GEN-LAST:event_txtNumeroKeyReleased

    private void txtCodigoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoKeyReleased

    private void txtPrecioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPrecioKeyReleased
        // TODO add your handling code here:
        Validacion validar = new Validacion();
        validar.decimal(evt, txtPrecio);
    }//GEN-LAST:event_txtPrecioKeyReleased

    private void txtNumeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNumeroActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNumeroActionPerformed

    private void txtCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoActionPerformed

    private void mnuQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuQuitarActionPerformed
        // TODO add your handling code here:
        cmdQuitar.doClick();
    }//GEN-LAST:event_mnuQuitarActionPerformed

    /**
     * @param args the command line arguments
     */
    private String buscarSerie() {
        String serie = "";
        List<Serie> listaSeries = sm.buscarSeries(CSelecciones.articulo, configuraciones.getInstance().getSucursal());

        if (listaSeries != null && !listaSeries.isEmpty()) {
            serie = JOptionPane.showInputDialog("Ingrese un numero de serie");
            if (serie == null) {

                return null;
            } else {
                if (!sm.buscaSerie(CSelecciones.articulo, configuraciones.getInstance().getSucursal(), serie)) {
                    JOptionPane.showMessageDialog(rootPane, "No existe ese número de serie");

                    return null;
                } else {
                    for (int i = 0; i < proforma.getDetalleproformaList().size(); i++) {
                        if (proforma.getDetalleproformaList().get(i).getSerie().equals(serie)) {
                            JOptionPane.showMessageDialog(rootPane, "Ya ha ingresado ese número de serie");

                            return null;
                        }
                    }
                }


            }
            return serie;
        }
        return serie;
    }

    private void Calcular() {
        double subtotal = 0.0D;
        double iva = 0.0D;
        double desc = Double.parseDouble(String.valueOf(this.txtDescuento.getValue()));
        for (int i = 0; i < proforma.getDetalleproformaList().size(); i++) {
            subtotal += proforma.getDetalleproformaList().get(i).getCantidad() * proforma.getDetalleproformaList().get(i).getPrecioVenta();

            double sd = proforma.getDetalleproformaList().get(i).getCantidad() * proforma.getDetalleproformaList().get(i).getPrecioVenta();
            sd = sd - sd * desc / 100.0D;
            iva += sd * configuraciones.getInstance().getConfiguracion().getIva() / 100.0D;
        }

        double subtd = subtotal - subtotal * desc / 100.0D;
        double total = subtd + iva;
        proforma.setDescuento(desc);
        proforma.setIva(iva);
        proforma.setSubtotal(subtotal);
        proforma.setTotal(total);
        this.txtSubtotal.setText(CNumeros.Formato(subtotal));
        this.txtSubtotalD.setText(CNumeros.Formato(subtd));
        this.txtIVA.setText(CNumeros.Formato(iva));
        this.txtTotal.setText(CNumeros.Formato(total));
    }

    private void limpiaTodo() {
        CSelecciones.articulo = null;
        txtPrecio.setText("");
        txtCodigo.setText("");
        txtCantidad.setValue(1);
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VProforma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VProforma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VProforma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VProforma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.out.println("Error setting native LAF: " + e);
        }
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VProforma(new Cliente()).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdAgregar;
    private javax.swing.JButton cmdGuardar;
    private javax.swing.JButton cmdQuitar;
    private javax.swing.JTable dtgProforma;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JPopupMenu mnuAcciones;
    private javax.swing.JMenuItem mnuQuitar;
    private javax.swing.JSpinner txtCantidad;
    private javax.swing.JTextField txtCedula;
    private javax.swing.JTextField txtCliente;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JSpinner txtDescuento;
    private javax.swing.JTextField txtDireccion;
    private javax.swing.JTextField txtFecha;
    private javax.swing.JTextField txtIVA;
    private javax.swing.JTextField txtNumero;
    private javax.swing.JTextField txtPrecio;
    private javax.swing.JTextField txtSubtotal;
    private javax.swing.JTextField txtSubtotalD;
    private javax.swing.JTextField txtTelefono;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables

    private void agregarArticulo(double precio, String serie, int cantidad) {
        boolean existe = false;
        if (serie.equals("")) {
            for (int i = 0; i < proforma.getDetalleproformaList().size(); i++) {

                if (proforma.getDetalleproformaList().get(i).getIdArticulo().equals(CSelecciones.articulo) && proforma.getDetalleproformaList().get(i).getPrecioVenta() == precio) {
                    existe = true;
                    int nuevaCant = proforma.getDetalleproformaList().get(i).getCantidad() + cantidad;
                    if (nuevaCant > CSelecciones.articulo.getStock()) {

                        JOptionPane.showMessageDialog(rootPane, "No existen suficientes artículos en Stock", "Error", JOptionPane.ERROR_MESSAGE);
                        limpiaTodo();
                        return;
                    }
                    proforma.getDetalleproformaList().get(i).setCantidad(nuevaCant);
                    dtgProforma.setValueAt(nuevaCant, i, 0);
                    dtgProforma.setValueAt(CNumeros.Formato(precio * nuevaCant), i, 3);
                    Calcular();

                    break;
                }
            }
        }
        if (!existe) {
                Detalleproforma detalleproforma = new Detalleproforma();
                detalleproforma.setCantidad(cantidad);
                detalleproforma.setIdArticulo(CSelecciones.articulo);
                detalleproforma.setIdProforma(proforma);
                detalleproforma.setSerie(serie);
                detalleproforma.setPrecioVenta(precio);
                proforma.getDetalleproformaList().add(detalleproforma);
                String desc = detalleproforma.getIdArticulo().getDescripcion() + " " + detalleproforma.getIdArticulo().getMarca() + " " + detalleproforma.getIdArticulo().getModelo();
                if (!serie.equals("")) {
                    desc = desc + "SN: " + serie;
                }
                String[] producto = {detalleproforma.getCantidad().toString(), desc, CNumeros.Formato(precio), CNumeros.Formato(precio * cantidad)};
                modelo.addRow(producto);
                Calcular();
            
            

        }
    }
}
